package cn.cmcc.online.smsapi.sdk.net.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.XyHttpRunnable;
import cn.cmcc.online.smsapi.sdk.util.KeyManager;

 
class Check {
	
	 private static Map<String,String> read(Context ctx){
		LineNumberReader lr = null;
		try{
			final File f=new File(ctx.getApplicationContext().getFilesDir()+File.separator+"check.log");
			if(!f.exists()){
				f.createNewFile();
			}
			lr = new LineNumberReader(new FileReader(f));
			String line =null;
			Map<String,String> map =null;
			if (lr != null) {
				while((line =lr.readLine()) != null){
					if(map == null){
						map= new HashMap<String, String>();
					}
					//LogManager.i("line: "+line);
					String temp[]=line.split("=");
					map.put(temp[0], temp[1]);
				}	
			}
		    return map;
		}catch(Throwable e){
//			e.printStackTrace();
            LogManager.e(Constant.TAG, "read: ", e);

		}finally{
			try{
				if(lr != null){
				 lr.close();
				}
			}catch(Throwable e){
//				e.printStackTrace();
	            LogManager.e(Constant.TAG, "read: ", e);

			}
		}
		return null;
	}
	 private  static void write(Context ctx,boolean checkEnable){
		 FileOutputStream fos =null;
		try{
			checkTime = System.currentTimeMillis();
			Check.checkEnable=checkEnable;
			final File f=new File(ctx.getApplicationContext().getFilesDir()+File.separator+"check.log");
			if(f.exists()){
				f.delete();
			}
			f.createNewFile();
		    fos = new FileOutputStream(f,false);
		    fos.write(("checkEnable="+checkEnable+"\n").getBytes());
		    fos.write(("checkTime="+System.currentTimeMillis()+"\n").getBytes());
		    fos.flush();
	
		  
		}catch(Throwable e){
//			e.printStackTrace();
            LogManager.e(Constant.TAG, "write: ", e);

		}finally{
			try{
				if(fos != null){
				 fos.close();
			     fos =null;
				}
			}catch(Throwable e){
//				e.printStackTrace();
	            LogManager.e(Constant.TAG, "write: ", e);

			}
		}
 
	}
	static long checkTime=-1;
	static boolean checkEnable =false;
	static boolean  check(final Context ctx) throws Exception{
	
		if(checkTime == -1){
			@SuppressWarnings("deprecation")
			Map<String,String> map = read(ctx);
			if(map != null){
				checkEnable=Boolean.valueOf(map.get("checkEnable"));
				checkTime=Long.valueOf(map.get("checkTime"));
			}else{
				checkTime =0;
				checkEnable =true;
			}
	   }
		 
	    {
			 
			if(checkEnable == false || checkTime == 0  || checkTime+3600*1000*24 < System.currentTimeMillis()){
				//需要重新检测是否可用.
				new Thread(){
					public void run() {
						try {
							checkNet(ctx);
						} catch (Throwable e) {
//							e.printStackTrace();
				            LogManager.e(Constant.TAG, "check: ", e);

						} 
					};
				}.start();

			}
			if(checkTime ==0){
				return true;
			}
		}
	    if(checkEnable ==false){
	    	throw new Exception(" PLEASE CHECK NETWORK IS OK.");
	    }
	    return checkEnable;
	}
	  
     private static boolean checkIng =false;
	 private static void checkNet(final Context ctx)throws Exception{
		if (checkIng)
			return;
		checkIng = true;
		HttpURLConnection http = null;
		InputStream dis = null;
		boolean bl = false;
		try {
			KeyManager.initAppKey();
			String url = "http://sdk.bizport.cn:8081/check";
			URL urls = new URL(url);

			http = (HttpURLConnection) urls.openConnection();
			http.setConnectTimeout(40000);// 设置连接超时时间
			/* SDK-534 huangzhiqiang 20160712 start */
			http.setReadTimeout(40000);
			/* SDK-534 huangzhiqiang 20160712 end */
			http.setDoInput(true);
			http.setDoOutput(true);
			http.setRequestMethod("GET");
			http.setUseCaches(false);// 请求不使用缓存
			http.setInstanceFollowRedirects(true);
			http.setRequestProperty("channel", XyHttpRunnable.appKey);
			http.connect();

			int code = http.getResponseCode();

			if (code == HttpURLConnection.HTTP_OK) {
				dis = http.getInputStream();
				byte[] bt = new byte[1024 * 1];
				int len = -1;
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				try {
					while ((len = dis.read(bt)) != -1) {
						bos.write(bt, 0, len);
					}
				}
				catch (Throwable e) {
					// e.printStackTrace();
					LogManager.e(Constant.TAG, "checkNet: ", e);

				}
				bos.flush();
				bt = bos.toByteArray();

				String response = new String(bt, "UTF-8");
				// LogManager.i("response: "+response);
				if (response != null && response.equals("true")) {
					bl = true;
				}
				bos.close();
			}
		}
		catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "checkNet: ", e);
		}
		finally {
			try {
				if (dis != null) {
					dis.close();
				}
				if (http != null) {
					http.disconnect();// 关闭连接
				}
			}
			catch (Throwable e) {
				// e.printStackTrace();
				LogManager.e(Constant.TAG, "checkNet: ", e);

			}
		}
		try {

			// LogManager.i("bl : "+bl);
			write(ctx, bl);
		}
		catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "checkNet: ", e);

		}
		checkIng = false;
	}
}
